<?php

namespace app\index\validate;

use think\Validate;
use think\Db;

/**
 * auth验证器
 */
class User extends Validate
{

    protected $rule = [
        'captcha|验证码'
            => 'require|captcha',
        'email'
            => 'require|email',
        'username|用户名'
            => 'require|notNumber:1|checkName:1|unique:user',
        'password|密码'
            => 'require|min:6|max:16',
        'repassword'
            => 'confirm:password|require',
        'oldpassword|旧密码'
            => 'require|min:6|max:16',
    ];

    protected $message = [
        'email.email'           => ':attribute格式错啦',
        'email.exists'          => ':attribute不存在',
        'repassword.confirm'    => 'wtf 两次密码输入不一致',
        'username.notNumber'    => '用户名不能为纯数字',
        'username.checkName'    => '用户名长度只能为5-12个字符或2-12个汉字',
    ];

    protected $scene = [
        'register'
            => ['email' => 'require|email|unique:user', 'username', 'password', 'repassword', 'captcha'],
        'login'
            => ['email', 'password', 'captcha'],
        'modify_password'
            => ['password', 'repassword', 'captcha','oldpassword'],
        'reset_password_mail'
            => ['email' => 'require|email|exists:user', 'captcha'],
    ];

    // 自定义notNumber规则，非纯数字通过
    protected function notNumber($value, $rule)
    {
        return !is_numeric($value);
    }

    protected function checkName($value, $rule)
    {
        if (strlen($value) < 5 || mb_strlen($value) > 12) {
            return false;
        }
        return true;
    }

    // 自定义exists规则，与unique用法一致，返回结果相反
    protected function exists($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        $db = Db::name($rule[0]);
        $key = isset($rule[1]) ? $rule[1] : $field;

        if (strpos($key, '^')) {
            // 支持多个字段验证
            $fields = explode('^', $key);
            foreach ($fields as $key) {
                $map[$key] = $data[$key];
            }
        } elseif (strpos($key, '=')) {
            parse_str($key, $map);
        } else {
            $map[$key] = $data[$field];
        }

        $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
        if (isset($rule[2])) {
            $map[$pk] = ['neq', $rule[2]];
        } elseif (isset($data[$pk])) {
            $map[$pk] = ['neq', $data[$pk]];
        }

        if ($db->where($map)->field($pk)->find()) {
            return true;
        }
        return false;
    }
}
